<template>
  <div class="app-container">
    <div v-show="show">
      <u-page title="问卷调查">
        <div slot="header">
          <el-button type="primary" icon="el-icon-edit" @click="hdlOpen(newForm)">
            {{ textMap['create'] }}
          </el-button>
        </div>

        <u-filtered>
          <el-form :inline="true" :model="listQuery" class="search-form">
            <!--            <el-form-item label="时间范围">-->
            <!--              <u-date-time-picker v-model="searchDate" @change="changeSearchDate" />-->
            <!--            </el-form-item>-->
            <el-form-item label="标题" prop="cardNo">
              <el-input v-model="listQuery.title" placeholder="请输入标题" clearable />
            </el-form-item>
            <!--            <el-form-item label="状态" prop="status">-->
            <!--              <el-select v-model="listQuery.status" placeholder="状态" clearable>-->
            <!--                <el-option label="全部" value="" />-->
            <!--                <el-option label="未发布" value="0" />-->
            <!--                <el-option label="已发布" value="1" />-->
            <!--                <el-option label="已暂停" value="2" />-->
            <!--                <el-option label="已结束" value="3" />-->
            <!--              </el-select>-->
            <!--            </el-form-item>-->
            <el-form-item label="状态" prop="state">
              <u-status v-model="listQuery.state" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="hdlFilter">搜索</el-button>
            </el-form-item>
            <el-form-item>
              <el-dropdown>
                <el-button type="primary">
                  批量操作<i class="el-icon-arrow-down el-icon--right" />
                </el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item :disabled="selectData.length===0" @click.native="hdlDel">批量删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-form-item>
          </el-form>
        </u-filtered>

        <u-table
          index="index"
          :data="list"
          :loading="listLoading"
          :options="listOptions"
          :columns="columns"
          :pagination.sync="listQuery"
          :fetch="hdlList"
          @selection-change="hdlSelectChange"
        >
          <template v-slot:right>
            <el-table-column label="操作" align="center" fixed="right" width="200">
              <template slot-scope="{ row }">
                <el-button v-if="!row.state" type="text" @click="handleDesign(row)">题目设计</el-button>
                <el-button type="text" @click="handleAnalyze(row)">问卷分析</el-button>
                <el-button type="text" @click="handleEdit(row)">编辑</el-button>
                <el-button type="text" @click="hdlDelete(row.id, row.title)">删除</el-button>
              </template>
            </el-table-column>
          </template>
        </u-table>

      </u-page>
    </div>

    <!--  问卷新增/编辑  -->
    <u-dialog :title="textMap[dialogStatus]" :show.sync="dialogFormVisible" width="40%" @confirm="dialogStatus==='create'?handleCreate():handleUpdate()">
      <el-form ref="dialogForm" :rules="rules" :model="dataForm" label-width="100px">
        <el-tabs v-model="active">
          <el-tab-pane label="基本配置" name="first">

            <el-form-item prop="title" label="标题">
              <el-input v-model="dataForm.title" placeholder="问卷标题" clearable maxlength="30" show-word-limit />
            </el-form-item>
            <el-form-item label="问卷时间" prop="validityDate">
              <u-date-time-picker v-model="dataForm.validityDate" value-format="yyyy-MM-dd HH:mm:ss" style="width: 100%" />
            </el-form-item>
            <el-form-item label="描述" prop="content">
              <el-input v-model="dataForm.content" type="textarea" placeholder="描述" clearable rows="5" />
            </el-form-item>

            <el-form-item prop="recoveryLimit" label="回收限制">
              <el-input v-model="dataForm.recoveryLimit" placeholder="回收限制" clearable maxlength="30" show-word-limit style="width: 96%" /> 份
            </el-form-item>

          </el-tab-pane>
          <el-tab-pane label="推送配置" name="second">
<!--            <el-form-item label="开启推送" prop="push">-->
<!--              <el-switch v-model="dataForm.push" />-->
<!--            </el-form-item>-->
<!--            v-if="dataForm.push"-->
            <el-form-item  label="消费金额上限" prop="upperLimit">
              <el-input v-model="dataForm.upperLimit" placeholder="消费金额上限(咋天)" clearable />
              <u-tip-info title="不填默认全部" />
            </el-form-item>
<!--            v-if="dataForm.push"-->
            <el-form-item  label="消费金额下限" prop="lowerLimit">
              <el-input v-model="dataForm.lowerLimit" placeholder="消费金额下限(咋天)" clearable />
              <u-tip-info title="不填默认全部" />
            </el-form-item>
          </el-tab-pane>
<!--          v-if="dataForm.push"-->
          <el-tab-pane  label="黑名单" name="third">
            <el-form-item label="开启黑名单" prop="blackListEnabled">
              <el-switch v-model="dataForm.blackListEnabled" />
            </el-form-item>
            <div v-if="dataForm.blackListEnabled">
              <el-form-item label="黑名单" prop="blackList">
                <blacklist v-model="dataForm.blackList" style="width: 100%" />

                <el-input v-model="dataForm.blackContent" type="textarea" placeholder="批量操作名单,手机号" clearable rows="10" style="margin-top: 10px" />
                <u-tip-info title="格式: 手机号+换行或者英文逗号" />
              </el-form-item>

            </div>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </u-dialog>

    <!--  题目设计  -->
    <u-dialog title="题目设计" :show.sync="designdialogFormVisible" @confirm="handleTopic">
      <el-form v-for="(item, index) in topics" ref="dynamicValidateForm" :key="index" :model="item" :rules="rules">

        <el-card style="margin-bottom: 10px">
          <el-form-item>
            <el-divider>{{ '题目' + (index + 1) }}</el-divider>
          </el-form-item>
          <el-form-item
            label="标题"
            prop="title"
          >
            <el-row>
              <el-col :span="20">
                <el-input v-model="item.title" placeholder="请输入" />
              </el-col>
              <el-col :span="1" style="margin-left: 10px">
                <el-button type="primary" @click="removeTopic(item,index)">删除题目</el-button>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="类型" prop="type">
            <el-radio-group v-model="item.type" @change="handleRadioClick(item)">
              <el-radio :label="1">单选</el-radio>
              <el-radio :label="2">多选</el-radio>
              <el-radio :label="3">单行输入框</el-radio>
              <el-radio :label="4">多行输入框</el-radio>
            </el-radio-group>
          </el-form-item>
          <template v-if="item.type === 1 || item.type === 2">
            <el-form-item v-for="(itemO, indexO) in item.options" :key="indexO" label="选项">
              <el-row>
                <el-col :span="16">
                  <el-input v-model="itemO.value" />
                </el-col>
                <el-col :span="2" style="margin-left: 10px;">
                  <el-checkbox v-if="isLastOption(item, indexO)" v-model="itemO.isInput" @change="isInputClick(itemO)">可输入</el-checkbox>
                </el-col>
                <el-col v-if="isLastOption(item, indexO)" :span="2" style="margin-left: 10px">
                  <el-button @click="addOptions(item)">添加选项</el-button>
                </el-col>
                <el-col :span="2" style="margin-left: 10px;">
                  <el-button @click="removeOption(item,indexO)">删除选项</el-button>
                </el-col>
              </el-row>

              <template v-if="itemO.isInput">
                <div v-for="(itemT,indexT) in itemO.unNo" :key="indexT">
                  <el-form-item
                    label="标题"
                    prop="untitle"
                    style="margin-top: 20px;margin-left: 40px;"
                  >
                    <el-row>
                      <el-col :span="20">
                        <el-input v-model="itemT.untitle" placeholder="请输入" />
                      </el-col>
                    </el-row>
                  </el-form-item>

                  <el-form-item label="类型" prop="untype" style="margin-top: 20px;margin-left: 40px;">
                    <el-radio-group v-model="itemT.untype" @change="handleunRadioClick(itemT)">
                      <el-radio :label="1">单选</el-radio>
                      <el-radio :label="2">多选</el-radio>
                      <el-radio :label="3">多行输入框</el-radio>
                    </el-radio-group>
                  </el-form-item>

                  <template v-if="itemT.untype == 1 || itemT.untype == 2">
                    <el-form-item v-for="(itemV,indexV) in itemT.unoptions" :key="indexV" label="选项" style="margin-top: 20px;margin-left: 40px;">
                      <el-row>
                        <el-col v-if="itemT.untype == 1 || itemT.untype == 2" :span="16">
                          <el-input v-model="itemV.unvalue" />
                        </el-col>
                        <el-col v-if="isLastunOption(itemT, indexV)" :span="2" style="margin-left: 10px">
                          <el-button @click="addunOptions(itemT)">添加选项</el-button>
                        </el-col>
                        <el-col :span="2" style="margin-left: 10px;">
                          <el-button @click="removeunOption(itemT,indexV)">删除选项</el-button>
                        </el-col>
                      </el-row>
                    </el-form-item>
                  </template>

                </div>
              </template>
            </el-form-item>
          </template>

          <el-form-item label="必填">
            <el-switch v-model="item.required" class="panel-switch" />
          </el-form-item>
        </el-card>

      </el-form>

      <el-button type="primary" @click="addTopic">添加题目</el-button>
    </u-dialog>
    <!-- 问卷分析 -->
    <u-dialog title="问卷分析" :show.sync="dialogVisibleAnalyze" :footer="false">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="答卷回收" name="first">
          <u-filtered>
            <el-form :inline="true" :model="analyzeQuery" class="search-form">
              <el-form-item label="卡号" prop="memberId">
                <el-input v-model="analyzeQuery.memberId" placeholder="请输入卡号" clearable />
              </el-form-item>
              <el-form-item label="手机号" prop="memberId">
                <el-input v-model="analyzeQuery.phone" placeholder="请输入卡号" clearable />
              </el-form-item>
              <el-form-item label="提交时间">
                <u-date-time-picker v-model="searchDate" @change="changeSearchDateAnalyze" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" @click="hdlFilteranalyze">查询</el-button>
                <el-button type="primary" icon="el-icon-download" @click="handleDownload">导出</el-button>
              </el-form-item>
            </el-form>
          </u-filtered>
          <u-table
            index="index"
            :data="analyzeDataForm"
            :loading="listLoading"
            :options="analyzeOptions"
            :columns="analyzeColumns"
            :pagination.sync="analyzeQuery"
            :fetch="hdlFilteranalyze"
          >
            <template v-slot:right>
              <el-table-column label="操作" align="center" fixed="right" width="200">
                <!--                slot-scope="{ row }"-->
                <template slot-scope="{ row }">
                  <el-button type="text" @click="fetchClick(row)">查看</el-button>
                </template>
              </el-table-column>
            </template>
          </u-table>
        </el-tab-pane>
        <el-tab-pane label="单题分析" name="second">

          <u-filtered style="border: none;margin: 0 0;margin-top: -10px">
            <el-form :inline="true" :model="analyzeQuery" style="margin:0 0;padding: 0 0;">
              <el-form-item label="提交时间">
                <u-date-time-picker v-model="searchDate" @change="changeSearchDateAnalyze" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" @click="analysis">查询</el-button>
                <el-button type="primary" icon="el-icon-download" @click="handleDownloadSecond">导出</el-button>
                <el-button type="primary" icon="el-icon-download" @click="handleDownloadMonthly">月份导出</el-button>
              </el-form-item>
            </el-form>
          </u-filtered>
          <el-row>

            <el-col style="padding: 10px 0;white-space: nowrap; overflow: hidden; text-overflow: ellipsis;" :span="4">
              <span style="">答卷数量：{{ analyzeQuery.totalCount }}</span>
            </el-col>
            <!--            <el-col :span="2" style="text-align: center;">-->
            <!--              <el-button type="primary" icon="el-icon-download" @click="handleDownloadSecond">导出</el-button>-->
            <!--            </el-col>-->
            <el-col style="margin-top: 10px">
              <span>只分析选择题目，不分析填选题目</span>
            </el-col>
          </el-row>

          <el-row style="display: flex; align-items: center; border: 1px solid #c0c4cc; background-color: #F9F9F9; font-weight: bold; height: auto;line-height: 40px;margin: 20px 0;">
            <el-col style="padding-left: 10px;" :span="9">
              <span>题目</span>
            </el-col>
            <el-col style="padding-left: 10px;border-left: 1px solid #c0c4cc" :span="9">
              <span>选项</span>
            </el-col>
            <el-col :span="3" style="border-left: 1px solid #c0c4cc;border-right: 1px solid #c0c4cc;padding-left: 5px;">
              <span>答卷数量</span>
            </el-col>
            <el-col :span="3" style="padding-left: 5px;">
              <span>占比</span>
            </el-col>
          </el-row>
          <el-form
            v-for="(item, index) in questionnaireAnalysis"
            v-if="item.type === 1 || item.type === 2"
            :key="index"
            :model="item"
            style="margin: 20px 0;margin-top: -20px"
          >
            <el-form-item class="list-item-item">
              <div style="display: flex" :style="{'background-color': (currentIndexPlusOne(index) % 2 === 0) ? '#f0f9eb' : ''}">
                <div style="width: 37.55%;  align-items: center; display: flex; justify-content: flex-start; border-right: 1px solid #c0c4cc;padding-left: 20px ">
                  <el-tooltip class="item" effect="dark" :content="currentIndexPlusOne(index) + '. ' + item.title + (item.type == 1 ? '【单选】' : item.type == 2 ? '【多选】' : '')" placement="top-start">
                    <div style="-webkit-box-orient: vertical; -webkit-line-clamp: 3; display: -webkit-box; text-overflow: ellipsis; white-space: normal; overflow: hidden;">
                      {{ currentIndexPlusOne(index) }}. {{ item.title }}{{ item.type == 1 ? '【单选】' : item.type == 2 ? '【多选】' : '' }}
                    </div>
                  </el-tooltip>
                </div>
                <div style="display: flex; flex-direction: column; flex-grow: 1; margin-left: -1px; margin-right: -10px; justify-content: center;">
                  <div v-for="(itemO, indexO) in item.options" :key="indexO" class="options">
                    <div style="width: 59.39%; padding-left: 10px;">{{ itemO.value }}</div>
                    <div style="width: 19.65%; padding-left: 10px;border-left: 1px solid #c0c4cc;border-right: 1px solid #c0c4cc;">{{ itemO.trueCount }}</div>
                    <div style="width: 14.3%; padding-left: 10px;">{{ itemO.percentage }}%</div>
                  </div>
                </div>
              </div>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </u-dialog>

    <recall v-if="!show" :row.sync="recalldataForm" @show="show = true" />
  </div>

</template>

<script>

import recall from '@/views/plugins/questionnaire/components/recallQuestionnaire.vue'
import item from '@/layout/components/Sidebar/Item.vue'
import Vue from 'vue'
import { title } from '@/config/settings'
import blacklist from '@/components/module/blacklist.vue'
export default {
  components: {
    blacklist,
    recall
  },
  data() {
    return {
      api: this.$u.api.PluginsQuestionnaireNewlist,
      isEditing: true,
      list: [],
      listOptions: {
        index: true,
        mutiSelect: true,
        stripe: true
      },
      // 表格
      columns: [
        {
          prop: 'title',
          label: '标题'
        },
        // {
        //   prop: 'beginTime',
        //   label: '开始时间'
        // },
        // {
        //   prop: 'endTime',
        //   label: '结束时间'
        // },
        // {
        //   prop: 'push',
        //   label: '是否推送',
        //   render: (h, params) => {
        //     const { push } = params.row
        //     if (push === true) {
        //       return h('el-tag', { props: { type: 'success' }}, '推送')
        //     } else if (push === false) {
        //       return h('el-tag', '不推送')
        //     }
        //   }
        // },
        {
          prop: 'validityDate',
          label: '有效期日期',
          width: '180',
          render: (h, params) => {
            let { beginTime, endTime } = params.row
            if (!beginTime) {
              beginTime = '不限制'
            }
            if (!endTime) {
              endTime = '不限制'
            }
            return [
              h('el-tag', { props: { effect: 'plain' }}, '起始:' + beginTime),
              h('br'),
              h('el-tag', { props: { effect: 'plain' }}, '终止:' + endTime)
            ]
          }
        },
        // {
        //   prop: 'status',
        //   label: '状态',
        //   render: (h, params) => {
        //     const { status } = params.row
        //     let title = ''
        //     let type = ''
        //     if (status === 0) {
        //       title = '未发布'
        //       type = 'success'
        //     }
        //     if (status === 1) {
        //       title = '已发布'
        //     }
        //     if (status === 2) {
        //       title = '已暂停'
        //       type = 'error'
        //     }
        //     if (status === 3) {
        //       title = '已结束'
        //       type = 'info'
        //     }
        //     return h('el-tag', { props: { type }}, title)
        //   }
        // },
        {
          prop: 'state',
          label: '状态',
          render: (h, params) => {
            const { state } = params.row
            let tooltipContent = ''

            if (state) {
              tooltipContent = '已开启' // 当开关状态为真时显示的提示内容
            } else {
              tooltipContent = '已关闭' // 当开关状态为假时显示的提示内容
            }

            return h('el-tooltip', {
              props: {
                content: tooltipContent
              }
            }, [
              h('el-switch', {
                props: {
                  value: state
                },
                on: {
                  change: (value) => {
                    this.handleUpdateSwitch(params.row, value)
                  }
                }
              })
            ])
          }
        },
        {
          prop: 'recycledObject',
          label: '已回收',
          render: (h, params) => {
            return h('el-tag', params.row.recycledObject)
          }
        },
        {
          prop: 'recoveryLimit',
          label: '回收限制',
          render: (h, params) => {
            if (params.row.recoveryLimit) {
              return h('el-tag', params.row.recoveryLimit)
            } else {
              return h('el-tag', { props: { type: 'success' }}, '不限制')
            }
          }
        },
        {
          prop: 'createdAt',
          label: '创建时间',
          timestamp: true
        }
      ],

      listQuery: {
        pageNumber: 1,
        pageSize: 20,
        totalCount: 1,
        title: '',
        beginTime: '',
        endTime: '',
        state: ''
      },
      // 查询时间范围
      searchDate: [],
      newForm: {
        state: false
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑问卷',
        create: '新增问卷'
      },
      dataForm: {},
      rules: {
        validityDate: [
          { required: true, message: '时间必选', trigger: 'blur' }
        ],
        title: [
          { required: true, message: '请设置标题', trigger: ['blur'] }
        ],
        type: [
          { required: true, message: '请设置类型', trigger: ['blur'] }
        ]

      },
      // 删除选中数据
      selectData: [],
      designdialogFormVisible: false,
      designdataForm: {},
      // 设计题目集合
      topics: [
        {
          options: [{ value: '' }],
          type: ''
        }
      ],
      questionnaireId: '',
      dialogVisibleAnalyze: false,
      active: 'first',
      activeName: 'first',
      // 用户提交数据
      analyzeDataForm: [],
      // 问卷提交表格
      analyzeColumns: [
        {
          prop: 'memberId',
          label: '卡号'
        },
        {
          prop: 'phone',
          label: '手机号'
        },
        {
          prop: 'createdAt',
          label: '提交时间',
          timestamp: true
        }, {
          prop: 'submitCount',
          label: '提交次数'
        }
      ],
      // 问卷提交列表
      analyzeQuery: {
        pageNumber: 1,
        pageSize: 10,
        totalCount: 1,
        memberId: '',
        phone: ''
      },
      analyzeOptions: {
        index: true
      },
      show: true,
      recalldataForm: {},
      // 问卷分析
      questionnaireAnalysis: {},
      currentIndex: 0
    }
  },
  computed: {
    item() {
      return item
    },
    currentIndexPlusOne() {
      const seenItems = {}
      let count = 0
      return (index) => {
        if (!seenItems[index]) {
          seenItems[index] = true
          count++
        }
        return count
      }
    }
  },
  created() {
    this.hdlList()
  },
  methods: {
    // 各月导出
    async handleDownloadMonthly() {
      const data = {
        questionnaireId: this.analyzeQuery.questionnaireId,
        createdAt: this.analyzeQuery.createdAt,
        updatedAt: this.analyzeQuery.updatedAt
      }
      const res = await this.api.analysisMonthly(data)

      res.data.forEach(item => {
        this.$set(item, 'January', item.January ? item.January + '%' : '')
        this.$set(item, 'February', item.February ? item.February + '%' : '')
        this.$set(item, 'March', item.March ? item.March + '%' : '')
        this.$set(item, 'April', item.April ? item.April + '%' : '')
        this.$set(item, 'May', item.May ? item.May + '%' : '')
        this.$set(item, 'June', item.June ? item.June + '%' : '')
        this.$set(item, 'July', item.July ? item.July + '%' : '')
        this.$set(item, 'August', item.August ? item.August + '%' : '')
        this.$set(item, 'September', item.September ? item.September + '%' : '')
        this.$set(item, 'October', item.October ? item.October + '%' : '')
        this.$set(item, 'November', item.November ? item.November + '%' : '')
        this.$set(item, 'December', item.December ? item.December + '%' : '')
        this.$set(item, 'monthlyAverage', item.monthlyAverage ? item.monthlyAverage + '%' : '')
      })

      const tHeader = ['题目', '一月满意/占比', '二月满意/占比', '三月满意/占比', '4月满意/占比', '5月满意/占比', '6月满意/占比', '7月满意/占比', '8月满意/占比', '9月满意/占比', '10月满意/占比', '11月满意/占比', '12月满意/占比', '各月平均']
      const filterVal = ['title', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', 'monthlyAverage']
      const datas = res.data.map(v => filterVal.map(j => { return v[j] }))
      this.$u.exports.excel('各月满意占比', tHeader, datas)
    },
    // 导出文件分析
    handleDownloadSecond() {
      const newArray = Object.values(this.questionnaireAnalysis).map(item => {
        return item
      })
      const newArray2 = []

      newArray.forEach((data, dataIndex) => {
        const newObj = {
          title: data.title,
          type: data.type,
          totalCount: this.analyzeQuery.totalCount
        }
        data.options.forEach((option, optionIndex) => {
          if (data.type === 1 || data.type === 2) {
            newObj[`percentage${optionIndex + 1}`] = option.percentage
            newObj[`trueCount${optionIndex + 1}`] = option.trueCount
          } else if (data.type === 3 || data.type === 4) {
            newObj['value'] = option.value
          }
        })
        newArray2.push(newObj)
      })
      const list = newArray2
      // 业务数据处理
      list.forEach(item => {
        this.$set(item, 'title', item.type === 1 ? item.title + '【单选】' : item.type === 2 ? item.title + '【多选】' : item.type === 3 ? item.title + '【输入】' : item.title + '【输入】')
        if (item.type === 1 || item.type === 2) {
          this.$set(item, 'percentage1', item.percentage1 + '%')
        }
        // this.$set(item, 'phone', item.phone ? item.phone : '')
        // this.$set(item, 'submitCount', item.submitCount ? item.submitCount : '')
      })
      // 表头&表数据
      const tHeader = ['题目', '满意', '一般', '不满意', '参评人数', '满意占比']
      const filterVal = ['title', 'trueCount1', 'trueCount2', 'trueCount3', 'totalCount', 'percentage1']
      const data = list.map(v => filterVal.map(j => { return v[j] }))
      this.$u.exports.excel('问卷分析记录', tHeader, data)
    },
    // 转换时间戳
    timestamp(time) {
      const timestamp = time // 例如，表示 2021 年 9 月 1 日 00:00:00 的时间戳
      const date = new Date(timestamp)

      const year = date.getFullYear() // 获取年份
      const month = date.getMonth() + 1 // 获取月份（注意：月份从 0 开始，所以要加 1）
      const day = date.getDate() // 获取日期

      const hours = date.getHours() // 获取小时
      const minutes = date.getMinutes() // 获取分钟
      const seconds = date.getSeconds() // 获取秒数

      const formattedDate = `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}` // 格式化日期
      const formattedTime = ` ${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}` // 格式化时间

      return formattedDate + formattedTime
    },
    modifyData(data) {
      const result = []
      const newResult = []
      // for (const key in data) {
      //   result[key] = []
      //   const arr = data[key][0]
      //   for (let i = 0; i < arr.length; i++) {
      //     const obj = arr[i]
      //     const modifiedOptions = {}
      //     const disabledIndices = []
      //     for (const optionKey in obj) {
      //       if (obj[optionKey].type === 3 || obj[optionKey].type === 4) {
      //         disabledIndices.push(obj[optionKey].value)
      //       } else if ('disabled' in obj[optionKey] && obj[optionKey].disabled === true) {
      //         if (obj[optionKey].type === 1) {
      //           const choose = optionKey === '0' ? '满意' : optionKey === '1' ? '一般' : optionKey === '2' ? '不满意' : ''
      //           disabledIndices.push(choose)
      //         } else {
      //           disabledIndices.push(obj[optionKey].value)
      //         }
      //       }
      //       if (obj[optionKey].unNo) {
      //         const unNoData = obj[optionKey].unNo
      //         unNoData.forEach((itemun) => {
      //           const groupDisabledIndicesForItemun = [] // 存储每个 itemun 的元素
      //           itemun.unoptions.forEach((itemuno) => {
      //             groupDisabledIndicesForItemun.push(itemuno.undisabled)
      //           })
      //           groupDisabledIndices.push(groupDisabledIndicesForItemun.join(','))
      //         })
      //       }
      //     }
      //     if (disabledIndices.length > 0) {
      //       for (let j = 0; j < disabledIndices.length; j++) {
      //         const optionsIndex = i + 1
      //         const optionsKey = `options${optionsIndex}`
      //         modifiedOptions[optionsKey] = disabledIndices.join(',')
      //       }
      //     } else {
      //       const optionsIndex = i + 1
      //       const optionsKey = `options${optionsIndex}`
      //       modifiedOptions[optionsKey] = ''
      //     }
      //     result[key].push(modifiedOptions)
      //   }
      // }

      for (const key in data) {
        result[key] = []
        const arr = data[key][0]
        for (let i = 0; i < arr.length; i++) {
          const obj = arr[i]
          const objLength = Object.keys(obj).length
          const modifiedOptions = {}
          const disabledIndices = []
          const groupDisabledIndices = []
          const modifiedGroupOptions = {}
          for (const optionKey in obj) {
            if (obj[optionKey].type === 3 || obj[optionKey].type === 4) {
              disabledIndices.push(obj[optionKey].value)
            } else if ('disabled' in obj[optionKey] && obj[optionKey].disabled === true) {
              if (obj[optionKey].type === 1) {
                if (objLength === 2) {
                  // const choose = optionKey === '0' ? '有' : optionKey === '1' ? '没有' : ''
                  const choose = obj[optionKey].value
                  disabledIndices.push(choose)
                } else {
                  const choose = optionKey === '0' ? '满意' : optionKey === '1' ? '一般' : optionKey === '2' ? '不满意' : '无法评价'
                  disabledIndices.push(choose)
                }
              } else {
                disabledIndices.push(obj[optionKey].value)
              }
            }
            if (obj[optionKey].unNo) {
              const unNoData = obj[optionKey].unNo
              unNoData.forEach((itemun) => {
                if (itemun.untitle) {
                  const groupDisabledIndicesForItemun = []
                  itemun.unoptions.forEach((itemuno, indexuno) => {
                    if (itemuno.undisabled === true) {
                      groupDisabledIndicesForItemun.push(itemuno.unvalue)
                    } else if (itemun.untype === 3) {
                      groupDisabledIndicesForItemun.push(itemuno.unvalue)
                    }
                  })
                  groupDisabledIndices.push(groupDisabledIndicesForItemun.join(','))
                }
              })
            }
          }

          const optionsIndex = i + 1
          const optionsKey = `options${optionsIndex}`
          if (disabledIndices.length > 0) {
            modifiedOptions[optionsKey] = disabledIndices.join(',')
          } else {
            modifiedOptions[optionsKey] = ''
          }
          result[key].push(modifiedOptions)
          const groupOptionsKey = `groupOptions${optionsIndex}`
          if (groupDisabledIndices.length > 0) {
            modifiedGroupOptions[groupOptionsKey] = groupDisabledIndices.join(',')
            // console.log(modifiedGroupOptions[groupOptionsKey])
          } else {
            // modifiedGroupOptions[groupOptionsKey] = ''
          }
          result[key].push(modifiedGroupOptions)
        }
      }
      const updatedResult = []

      for (const key in result) {
        updatedResult[key] = result[key].map((item, index) => {
          if (Object.keys(item).length > 0) {
            return item
          }
        }).filter(item => item !== undefined)
      }
      return updatedResult
    },

    // 辅助函数：提取数字后缀并进行排序
    extractAndSortKeys(obj, prefix) {
      const keys = Object.keys(obj)
        .filter((key) => key.startsWith(prefix))
        .map((key) => parseInt(key.slice(prefix.length)))

      keys.sort((a, b) => a - b)

      return keys.map((key) => prefix + key)
    },

    handleDownload() {
      const list = this.$u.deepClone(this.analyzeDataForm)

      // 新数组
      const newObj = []
      // 表头
      const tHeaders = ['会员卡号', '手机号', '提交时间', '提交次数']
      const filterVal = ['memberId', 'phone', 'createdAt', 'submitCount']

      // let memberId = ''
      let id = ''
      // 题目
      const topicList = {}
      list.forEach((item, indexs) => {
        newObj.push(
          {
            id: item.id,
            memberId: item.memberId,
            phone: item.phone,
            createdAt: this.timestamp(item.createdAt),
            submitCount: item.submitCount
          }
        )

        const sortedQuestions = item.recyclingQuestions.sort((a, b) => {
          const typeA = a.type
          const typeB = b.type

          if (typeA === 1 && typeB !== 1) {
            return -1
          }

          if (typeA !== 1 && typeB === 1) {
            return 1
          }

          if (typeA === 2 && typeB !== 2) {
            return -1
          }

          if (typeA !== 2 && typeB === 2) {
            return 1
          }

          return typeA - typeB
        })
        const idMap = {}
        for (const [index, items] of sortedQuestions.entries()) {
          if (indexs === 0) {
            tHeaders.push((index + 1) + '. ' + (items.type === 1 ? (items.title + '【单选】') : items.type === 2 ? (items.title + '【多选】') : (items.type === 3 || items.type === 4) ? (items.title + '【填空】') : ''))
          }
          items.options.forEach(itemxx => {
            if (itemxx.unNo) {
              itemxx.unNo.forEach(itemun => {
                if (indexs === 0) {
                  tHeaders.push(itemun.untitle)
                }
              })
            }
            itemxx.type = items.type
          })

          const { id, ...rest } = items.options

          if (id in idMap) {
            idMap[id].push(rest)
          } else {
            idMap[id] = [rest]
          }
        }
        const itemTopicList = Object.values(idMap)
        // memberId = item.memberId
        // topicList[item.memberId] = itemTopicList

        id = item.id
        topicList[item.id] = itemTopicList
      })
      const modifiedData = this.modifyData(topicList)

      const optionsKeys = modifiedData[id].map(item => Object.keys(item)).join(',')
      const str = optionsKeys
      const optionsArray = str.split(',') // 拆分成数组
      const quotedOptions = optionsArray.map(option => option.replace(/'/g, '')) // 去除选项名称周围的单引号
      const result = [...quotedOptions] // 将选项数组与其他元素合并
      filterVal.push(...result)

      const finalObj = newObj.map((member) => {
        // const memberId = member.memberId
        const id = member.id
        const options = {}
        // const groupOptions = {}
        modifiedData[id].forEach((option) => {
          for (const key in option) {
            if (key.startsWith('options') || key.startsWith('groupOptions')) {
              const optionValue = option[key]
              const optionKey = key
              options[optionKey] = optionValue
            }
          }
        })
        return { ...member, ...options }
      })
      console.log(finalObj)
      const tHeader = [...new Set(tHeaders)]
      // console.log(tHeader)
      // console.log(filterVal)
      // console.log(finalObj)
      const data = finalObj.map(v => filterVal.map(j => { return v[j] }))
      this.$u.exports.excel('问卷分析记录', tHeader, data)
    },

    // 判断是否是最后一个选项
    isLastunOption(itemT, indexV) {
      return indexV === itemT.unoptions.length - 1
    },
    // 删除选项
    removeunOption(itemT, indexT) {
      itemT.unoptions.splice(indexT, 1)
    },
    // 添加选项
    addunOptions(item) {
      item.unoptions.push({ unvalue: '', undisabled: false })
    },
    handleunRadioClick(item) {
      // 处理选项点击的逻辑
      if (item.untype === 3) {
        item.unoptions = [{ unvalue: '' }]
        return
      }
      if ((item.untype === 1 || item.untype === 2) && item.unoptions.length === 0) {
        // 添加新的选项
        this.addunOptions(item)
      }
    },
    isInputClick(itemO) {
      if (itemO.isInput) {
        // 添加一个空数组属性
        Vue.set(itemO, 'unNo', [])
        // 或者使用 this.$set(itemO, 'unOptions', []);

        // 添加一个初始输入框
        itemO.unNo.push({ untitle: '', unoptions: [] })
      } else {
        // 移除数组属性
        this.$delete(itemO, 'unNo')
      }
    },
    async handleUpdateSwitch(row, value) {
      const self = this
      const res = await self.api.queryAllByQuestionnaireId(row.id).then()
      if (Object.keys(res.data).length !== 0) {
        row.state = value
        // 提交更新数据
        self.api.update(row).then(() => {
          // 刷新数据列表
          self.hdlList()
          // 通知信息
          self.$u.msg('更新成功')
        })
      } else {
        self.$confirm('请先添加问卷题目在开启', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          self.handleDesign(row)
        }).catch(() => {
          self.$message({
            type: 'info',
            message: '已取消开启'
          })
        })
      }
    },
    // 问卷分析
    analysis() {
      const data = {
        questionnaireId: this.analyzeQuery.questionnaireId,
        createdAt: this.analyzeQuery.createdAt,
        updatedAt: this.analyzeQuery.updatedAt
      }
      const self = this
      self.api.recyleQuestionnaireAnalysis(data).then(res => {
        self.questionnaireAnalysis = res.data.analyzeData
        self.analyzeQuery.totalCount = res.data.totalCount
      })
      // self.api.recyleQuestionnaireAnalysis(self.analyzeQuery.questionnaireId).then(res => {
      //   self.questionnaireAnalysis = res.data
      // })
    },
    // 问卷提交列表
    recycleList() {
      const self = this
      self.api.recycleList(self.analyzeQuery).then(res => {
        res.data.list.forEach(item => {
          const recyclingQuestions = JSON.parse(item.recyclingQuestions)
          item.recyclingQuestions = recyclingQuestions
          item.recyclingQuestions.forEach(itemR => {
            const options = JSON.parse(itemR.options)
            itemR.options = options
          })
        })
        self.analyzeDataForm = res.data.list
        self.analyzeQuery.totalCount = res.data.totalCount
      })
    },

    // 打开修改弹窗
    handleEdit(row) {
      this.isEditing = false
      const { beginTime, endTime } = row
      row.validityDate = []
      if (beginTime && endTime) {
        row.validityDate = [beginTime, endTime]
      }
      this.hdlEdit(row)
    },
    fetchClick(row) {
      this.recalldataForm = row
      this.dialogVisibleAnalyze = false
      this.show = false
      // window.open('/member/list', '_blank')
    },
    // 问卷提交数据 时间切换查询
    changeSearchDateAnalyze(item) {
      if (item) {
        this.analyzeQuery.createdAt = item[0]
        this.analyzeQuery.updatedAt = item[1]
      } else {
        this.analyzeQuery.createdAt = ''
        this.analyzeQuery.updatedAt = ''
      }
    },
    // 查询问卷提交数据
    hdlFilteranalyze() {
      this.listQuery.page = 1
      const self = this
      self.api.recycleList(self.analyzeQuery).then(res => {
        res.data.list.forEach(item => {
          const recyclingQuestions = JSON.parse(item.recyclingQuestions)
          item.recyclingQuestions = recyclingQuestions
          item.recyclingQuestions.forEach(itemR => {
            const options = JSON.parse(itemR.options)
            itemR.options = options
          })
        })
        self.analyzeDataForm = res.data.list
        self.analyzeQuery.totalCount = res.data.totalCount
      })
    },
    // 问卷分析对话框，选择
    handleClick(tab, event) {
      if (tab.name === 'second') {
        this.analysis()
      } else if (tab.name === 'first') {
        this.recycleList()
      }
    },
    // 问卷分析
    handleAnalyze(row) {
      const self = this
      self.dialogVisibleAnalyze = true
      self.analyzeQuery.questionnaireId = row.id
      this.recycleList()
    },
    // 验证标题提交
    findEmptyData(data) {
      for (let i = 0; i < data.length; i++) {
        const item = data[i]
        const titleEmpty = item.title.trim() === ''
        const typeEmpty = item.type === undefined

        if (titleEmpty) {
          throw new Error('请填写题目 ' + (i + 1) + ' 的标题')
        }

        if (typeEmpty) {
          throw new Error('请选择题目 ' + (i + 1) + ' 的类型')
        }

        const emptyIndex = item.options.findIndex(option => option.value === '')
        if (emptyIndex !== -1 && (item.type === 1 || item.type === 2)) {
          throw new Error('请填写题目 ' + (i + 1) + ' 的选项中的第 ' + (emptyIndex + 1) + ' 选项答案')
        }
      }
    },
    // 题目新增
    handleTopic() {
      try {
        this.findEmptyData(this.topics)
      } catch (error) {
        // 处理错误，例如显示错误提示
        this.$message({
          message: error.message,
          type: 'error'
        })
        return // 如果发现错误，停止执行下一步代码
      }
      const transformedData = this.topics.map(item => {
        const { options, ...rest } = item
        const modifiedOptions = options.map(option => ({
          ...option,
          disabled: false
        }))
        return {
          ...rest,
          options: JSON.stringify(modifiedOptions)
        }
      })
      // const transformedObjects = this.topics.map(obj => ({
      //   ...obj,
      //   options: obj.options.map(option => option.value)
      // }))
      // if (transformedObjects.length === 0) {
      //   this.$message({
      //     message: '请添加题目',
      //     type: 'error'
      //   })
      //   return
      // }
      const id = this.questionnaireId
      const self = this
      self.api.createDesign(id, transformedData).then(() => {
        // 刷新数据列表
        self.hdlList()
        // 关闭弹窗状态
        self.designdialogFormVisible = false
        // 通知信息
        self.$u.msg('创建成功')
      })
    },
    // 题目类型选择
    handleRadioClick(item) {
      // 处理选项点击的逻辑
      if (item.type === 3 || item.type === 4) {
        // 清空选项数组
        item.options = [{ value: '' }]
        return
      }
      if ((item.type === 1 || item.type === 2) && item.options.length === 0) {
        this.addOptions(item)
      }
    },
    // 判断是否是最后一个选项
    isLastOption(item, indexO) {
      return indexO === item.options.length - 1
    },
    // 删除选项
    removeOption(item, indexO) {
      item.options.splice(indexO, 1)
    },
    // 添加选项
    addOptions(item) {
      item.options.push({ value: '' })
    },
    // 删除题目
    removeTopic(item, index) {
      const self = this
      if (item.id) {
        // 模态对话框组件
        self.$confirm('此操作将' + item.title + '删除后将不能恢复，是否继续删除？', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => {
          // 处理确认事件
          self.api.deleteByIdDesign(item.id).then(() => {
            // 通知信息
            self.$u.msg('删除成功')
            this.topics.splice(index, 1)
          })
        }).catch(() => {
        })
      } else {
        this.topics.splice(index, 1)
      }
    },
    // 添加题目
    addTopic() {
      this.topics.push({
        title: '',
        options: [{ value: '' }]
      })
    },
    // 题目设计
    handleDesign(row) {
      this.questionnaireId = row.id
      this.designdialogFormVisible = true
      const self = this
      self.api.queryAllByQuestionnaireId(row.id).then(res => {
        const modifiedData = res.data.map(item => {
          const options = JSON.parse(item.options)
          return {
            ...item,
            options
          }
        })
        this.topics = modifiedData
      })
    },
    // 新增事件
    handleCreate() {
      const { validityDate } = this.dataForm
      if (validityDate) {
        this.dataForm.beginTime = validityDate[0]
        this.dataForm.endTime = validityDate[1]
      }
      this.hdlCreate()
    },
    // 更新操作
    handleUpdate() {
      const { validityDate } = this.dataForm

      if (validityDate) {
        this.dataForm.beginTime = validityDate[0]
        this.dataForm.endTime = validityDate[1]
      }
      this.hdlUpdate()
    }
  }
}
</script>

<style scoped>
.el-row {
  &:last-child {
    margin-bottom: -50px;
  }
}

.list-header {
  background-color: #F9F9F9;
  font-weight: bold;
}
.list-item-item{
  border: 1px solid #c0c4cc;
  border-top: none;
}
.options{
  display: flex;
  border: 1px solid #c0c4cc;
  border-top: none;
  border-left: none;
}
.options:last-child{
  border-bottom: none;
}

</style>
